package cn.xwt.weidisk.util;

import cn.xwt.weidisk.pojo.dao.UserDo;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import java.util.Calendar;
import java.util.Date;

/**
 * @author 薛慰涛
 * 小工具类
 */
public class CommonUtils {

    /**
     * 随机生成5位数验证码
     * @return String
     */
    public static String getVerificationCode() {
        return String.valueOf((int)((Math.random()*9+1)*10000));
    }

    /**
     * 获取用户id
     * @return long
     */
    public static Long getUid() {
        try {
            return ((UserDo) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        } catch (Exception ignored) {
            return 0L;
        }
    }

    /**
     * 获取用户ip
     * @return String
     */
    public static String getIp() {
        WebAuthenticationDetails details = (WebAuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        return details.getRemoteAddress();
    }

    /**
     * 判断回收站中文件是否过期
     * @param deleteTime 文件删除时间
     * @return boolean
     */
    public static boolean isExpire(Date deleteTime) {
        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime();
        calendar.setTime(deleteTime);
        calendar.add(Calendar.DATE, 3);
        Date expire = calendar.getTime();
        return now.after(expire);
    }
}
